// pages/orderList/index.js
import Toast from '@vant/weapp/toast/toast';
import Dialog from '@vant/weapp/dialog/dialog';
import {
  serializeParams,
  matchDictList
} from "../../utils/index.js";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    feedList: [],
    value1: '1',
    poupShow: false,
    option1: [{
        text: "订单（全部）",
        value: "1"
      },
      {
        text: "订单（已完成）",
        value: "2"
      },
      {
        text: "订单（未完成）",
        value: "3"
      },
    ],
    value2: '1',
    option2: [{
        text: "下单时间（升序）",
        value: "1"
      },
      {
        text: "下单时间（降序）",
        value: "2"
      }
    ],
    admin: "0",
    refresherTriggered: false,
    active: 0,
    fileBasePath: "",
    dicts: [],
    // 查询参数
    queryParams: {
      pageSize: 10,
      pageNum: 1
    },
    isLoadMore: false, //加载更多
    isLoading: true,
    loading: false,
    total: 0,
    totalPage: 0,
    list: [] //订单列表
  },
  tabBarChange(e) {
    this.setData({
      active: e.detail
    });
    if (this.data.active == 1) {
      this.selectComponent("#AllOrders").initComponent();
    }
  },
  change1(e) {
    this.setData({
      value1: e.detail
    });
    this.onReady();
  },
  change2(e) {
    this.setData({
      value2: e.detail
    });
    this.onReady();
  },
  allOrdersSuccess(e) {
    const feedList = this.data.feedList;
    for (let i = 0; i < feedList.length; i++) {
      for (let j = 0; j < feedList[i].length; j++) {
        if (feedList[i][j]['_id'] == e.detail.id) {
          this.setData({
            [`feedList[${i}][${j}].success`]: '1'
          });
        }
      }
    }
  },
  successOrder(e) {
    Dialog.confirm({
        title: '提示',
        message: '是否完成该订单',
        // theme: 'round-button',
      })
      .then(async () => {
        // on confirm
        try {
          Toast.loading({
            message: '正在完成该订单',
            forbidClick: true,
            loadingType: 'spinner',
            mask: true
          });
          const res = await getApp().globalData.wxCloudRequest({
            type: "successOrder",
            openId: wx.getStorageSync("idInfo")['openid'],
            id: e.target.dataset.id
          });
          const feedList = this.data.feedList;
          for (let i = 0; i < feedList.length; i++) {
            for (let j = 0; j < feedList[i].length; j++) {
              if (feedList[i][j]['_id'] == e.target.dataset.id) {
                this.setData({
                  [`feedList[${i}][${j}].success`]: '1'
                });
              }
            }
          }
          Toast.clear();
          this.selectComponent("#AllOrders").setOrdersSuccess({
            id: e.target.dataset.id
          });
        } catch (error) {

        }
      })
      .catch(() => {
        // on cancel
      });

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {},
  async bindrefresherrefresh(e) {
    this.setData({
      ['queryParams.pageNum']: 1,
      loading: true
    });
    try {
      const {
        result: res
      } = await this.getList();

      this.setData({
        // list: res.data,
        feedList: [res.data],
        total: res.total,
        totalPage: res.totalPage,
        loading: false
      });
    } catch (error) {
      this.setData({
        // list: [],
        feedList: [],
        total: 0,
        totalPage: 0,
        loading: false
      });
    }
    this.setData({
      refresherTriggered: false
    })
  },
  binddragging(e) {},
  showDetail(e) {
    const params = {
      orderId: e.target.dataset.id,
      showDetail: true
    }
    wx.navigateTo({
      url: '/pages/orderSuccess/index?' + serializeParams(params),
    })
  },
  showImg(e) {
    const {
      item: imgList
    } = e.target.dataset;
    wx.previewImage({
      urls: imgList.map((item) => item.filePath)
    })
  },
  getList(list = []) {
    this.setData({
      isLoading: true
    })
    const {
      openid
    } = wx.getStorageSync("idInfo");
    return new Promise((resolve, reject) => {
      getApp().globalData.wxCloudRequest({
        type: "getOrderList",
        openId: openid,
        ...this.data.queryParams,
        // lastCreateTime:list.length?[...list].pop().createTime:null,
        success: this.data.value1,
        sortCreateTime: this.data.value2 == "1" ? "desc" : "asc"
      }).then((res) => {
        const r = {
          ...res,
          result: {
            ...res.result,
            data: res.result.data.map((item) => {
              return {
                ...item,
                customerData: {
                  ...item.customerData,
                  region: item.customerData.regionValue.join("") + item.customerData.address
                },
                sellerData: {
                  ...item.sellerData,
                  region: item.sellerData.regionValue.join("") + item.sellerData.address
                },
                lockInfo: {
                  ...item.lockInfo,
                  typeLabel: matchDictList(item.lockInfo.type, this.data.dicts, "dictValue", "dictLabel")
                }
              }
            })
          }
        }
        resolve(r);
        this.setData({
          isLoading: false
        })
      }).catch((err) => {
        reject(err);
        this.setData({
          isLoading: false
        })
      })
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: async function () {
    this.setData({
      dicts: getApp().globalData.dicts.lockType || wx.getStorageSync('dicts')["lockType"] || [],
      ["queryParams.pageNum"]: 1
    });
    Toast.loading({
      message: '加载中...',
      forbidClick: true,
      loadingType: 'spinner',
      mask: true
    });
    const {
      result: res
    } = await this.getList();
    this.setData({
      // list: res.data,
      feedList: [res.data],
      total: res.total,
      totalPage: res.totalPage
    });
    Toast.clear();
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: async function () {
    const fileBasePath = getApp().globalData.env == "develop" ? getApp().globalData.dev : getApp().globalData.prod;
    if (this.data.admin != wx.getStorageSync('idInfo')['admin']) {
      this.setData({
        active: 0
      })
    }
    this.setData({
      fileBasePath: fileBasePath,
      admin: wx.getStorageSync('idInfo')['admin'] || "0"
    })
    if (getApp().globalData.hasAdd) { //已经添加
      Toast.loading({
        message: '加载中...',
        forbidClick: true,
        loadingType: 'spinner',
        mask: true
      });
      this.setData({
        ['queryParams.pageNum']: 1
      })
      const {
        result: res
      } = await this.getList();
      this.setData({
        // list: res.data,
        feedList: [res.data],
        total: res.total,
        totalPage: res.totalPage
      });
      Toast.clear();
      getApp().globalData.hasAdd = false;
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: async function () {
    this.setData({
      ['queryParams.pageNum']: 1,
    });
    const {
      result: res
    } = await this.getList();
    this.setData({
      // list: res.data,
      feedList: [res.data],
      total: res.total,
      totalPage: res.totalPage
    });
    wx.stopPullDownRefresh();
  },
  bindscrolltolower() {
    this.onReachBottom();
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: async function () {
    if (this.data.queryParams.pageNum >= this.data.totalPage || this.data.isLoadMore) {
      return
    }
    this.setData({
      ['queryParams.pageNum']: this.data.queryParams.pageNum + 1,
      isLoadMore: true
    });
    const {
      result: res
    } = await this.getList(this.data.list);
    this.setData({
      // list: this.data.list.concat(res.data),
      [`feedList[${this.data.queryParams.pageNum-1}]`]: res.data,
      total: res.total,
      totalPage: res.totalPage,
      isLoadMore: false
    });
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})